<template>
  <div>
    <n-button size="medium" @click="drawBtn(), clear()">提现</n-button>
    <n-modal
      v-model:show="disabled"
      :mask-closable="false"
      preset="dialog"
      title="提现"
      style="height: 470px"
    >
      <n-form
        :label-width="80"
        :model="formValue"
        :rules="rules"
        size="medium"
        ref="formRef"
        label-placement="left"
        label-align="left"
      >
        <n-grid :cols="4">
          <n-gi span="4" style="margin-top: 18px">
            <n-form-item label="提现金额" path="withdrawAmount">
              <n-input
                type="number"
                v-model:value="formValue.withdrawAmount"
                placeholder="输入提现的金额"
                style="width: 100%"
                :on-input="inpputText"
              />
            </n-form-item>
          </n-gi>
          <n-gi span="3" style="margin-top: 18px">
            <n-form-item label="提现方式" path="withdrawMethod">
              <n-select
                :value="formValue.withdrawMethod"
                v-model:value="formValue.withdrawMethod"
                :options="options"
                :on-update:value="withdrawMethodChange"
                style="width: 60%"
              >
                <n-button>{{ WithDraw }}</n-button>
              </n-select>
              <n-tooltip trigger="click">
                <template #trigger>
                  <n-button class="button" @click="exchangeRate">?</n-button>
                </template>
                {{
                  `当前提现换算汇率为:${paritiesByNCLT}预计${hourByNCLT}小时后到账，预计产生手续费${serviceChargeByNCLT}`
                }}
              </n-tooltip>
            </n-form-item>
          </n-gi>
          <n-gi span="4" style="margin-top: 18px">
            <n-form-item label="支付账号" path="withdrawAcctNo">
              <n-input disabled v-model:value="formValue.withdrawAcctNo" />
            </n-form-item>
          </n-gi>
          <n-gi span="4" style="margin-top: 18px">
            <n-form-item label="目标账户" path="targetAcctNo">
              <n-input
                placeholder="输入目标账户"
                maxlength="30"
                v-model:value="formValue.targetAcctNo"
              />
            </n-form-item>
          </n-gi>
          <n-gi span="4" style="margin-top: 18px">
            <n-form-item label="持卡人" path="cardHolder">
              <n-input
                placeholder="输入持卡人姓名"
                maxlength="30"
                v-model:value="formValue.cardHolder"
                :disabled="cardHolderIsshow"
              />
            </n-form-item>
          </n-gi>
          <n-gi span="4" style="margin-top: 18px">
            <n-form-item path="txPassword" label="交易密码">
              <n-input
                v-model:value="formValue.txPassword"
                type="password"
                placeholder="输入交易密码 "
                maxlength="6"
              />
            </n-form-item>
          </n-gi>
          <n-gi span="4">
            <n-space justify="right" style="margin-top: 18px">
              <n-form-item>
                <n-space>
                  <n-button @click="(disabled = false), clear()" size="medium" strong secondary
                    >取消</n-button
                  >
                  <n-button
                    @click="Submit"
                    attr-type="button"
                    size="medium"
                    type="info"
                    :disabled="isShow"
                    >确认</n-button
                  >
                </n-space>
              </n-form-item>
            </n-space>
          </n-gi>
        </n-grid>
      </n-form>
    </n-modal>
  </div>
</template>
<script lang='ts' setup>
import { ref, onMounted, inject } from 'vue';
import { useMessage } from 'naive-ui';

import md5 from 'js-md5';
const message = useMessage();

const disabled = ref(false); // 是否显示模态框

const formRef = ref();

const paritiesByNCLT = ref('--'); // 法币提现汇率

const hourByNCLT = ref('24'); // 法币提现到账时间

const serviceChargeByNCLT = ref('--'); // 法币提现手续费

const paritiesByLink = ref('2222:2222'); // 链钱包汇率

const cardHolderIsshow = ref(false); // 持卡人默认禁用

const hourByLink = ref('22222'); // 链钱包到账时间

const serviceChargeByLink = ref('222222'); // 链钱包手续费

import { QuestionCircleOutlined } from '@vicons/antd';

import { drawMoney } from '@/api/drawMoney/drawMoney';

import { createStorage } from '@/utils/Storage';

import { getAccount } from '@/api/dashboard/getAccount';

import { getChainwallet } from '@/api/wthdrawalApply/getChainwallet'; // 连钱包

import { getExchangeRate } from '@/api/exchangeRate/exchangeRate'; // 当前汇率

const Storage = createStorage({ storage: localStorage });

let custNoValue = Storage.get('custNo');

const options = [
  {
    label: '提现到链钱包',
    value: '0',
  },
  {
    label: '提现到法币',
    value: '1',
  },
];
function inpputText(e) {
  console.log(e);
}
const isShow = ref(false);
// 更改提现方式，修改持卡人禁用状态，为提现方式赋值，请求链钱包提现地址
const WithDraw = ref('');
async function withdrawMethodChange(val) {
  if (val == '0') {
    console.log(val);
    isRequired.value = false;
    message.info('提现到链钱包');
    let res = await getChainwallet();
    console.log(res);
    formValue.value.targetAcctNo = res.data.body.address;
    cardHolderIsshow.value = true;
    formValue.value.withdrawMethod = '0';
  } else if (val == '1') {
    message.info('提现到法币');
    isRequired.value = true;
    console.log(val);
    WithDraw.value = val.label;
    formValue.value.targetAcctNo = '';
    cardHolderIsshow.value = false;
    formValue.value.withdrawMethod = '1';
  } else {
    WithDraw.value = '请选择提现方式';
  }
}

// 清除输入框
const clear = () => {
  formValue.value.withdrawAmount = '';
  formValue.value.withdrawAcctNo = '';
  formValue.value.targetAcctNo = '';
  formValue.value.txPassword = '';
  formValue.value.withdrawMethod = '请选择提现方式';
  formValue.value.cardHolder = '';
};

// 需要传递的参数
const formValue = ref({
  custNo: custNoValue,
  withdrawAmount: '',
  withdrawAcctNo: '',
  withdrawMethod: '请选择提现方式',
  targetAcctNo: '',
  txPassword: '',
  cardHolder: '',
   sysSign: '0',
});

// 获取目标账号打开提现模态框
async function drawBtn() {
  disabled.value = true;
  let custNo = Storage.get('custNo');
  let data = await getAccount({ custNo });
  formValue.value.withdrawAcctNo = data.data.body.acctNo;
}

// 从首页获取账户余额
const drawBalance = inject('drawBalance');
console.log(drawBalance);

// 输入过程中判断提现金额小于所持有的的余额
function amountVerification(rule, value) {
  return drawBalance.value >= value;
}

const isRequired = ref(true);
// 表单验证规则
const rules = {
  withdrawAmount: [
    {
      required: true,
      validator(rule, value) {
        if (!value) {
          return new Error('请输入提现金额');
        } else {
          return true;
        }
      },
      message: '请输入提现金额',
      trigger: 'blur',
    },
    {
      validator: amountVerification,
      message: '提现金额不可大于您持有的金额',
      trigger: 'input',
    },
  ],
  targetAcctNo: [
    {
      required: true,
      message: '请输入目标账户',
      trigger: 'blur',
    },
  ],
  cardHolder: [
    {
      required: false,
      message: '请输入持卡人',
      trigger: 'blur',
    },
  ],
  txPassword: [
    {
      required: true,
      message: '请输入交易密码',
      trigger: 'blur',
    },
  ],
  withdrawAcctNo: [
    {
      required: true,
      message: '请输入交易密码',
      trigger: 'blur',
    },
  ],
};

const rateValue = ref({
  amt: '',
  feeType: '',
});

// 获取当前充值汇率
async function exchangeRate() {
  if (formValue.value.withdrawAmount) {
    rateValue.value.amt = formValue.value.withdrawAmount;
    if (formValue.value.withdrawMethod == '0') {
      rateValue.value.feeType = '1';
    } else if (formValue.value.withdrawMethod == '1') {
      rateValue.value.feeType = '4';
    } else {
      message.info('查看汇率前，请先选择提现方式');
    }
    await getExchangeRate(rateValue.value).then((val) => {
      console.log(val);
      paritiesByNCLT.value = val.data.body.excRate;
      serviceChargeByNCLT.value = val.data.body.commissionAmount;
    });
  } else {
    message.info('查看汇率前，请先输入提现金额');
  }
}

// 验证结果输出
const Submit = (e) => {
  isShow.value = true;
  formRef.value.validate((errors) => {
    if (!errors) {
      if (formValue.value.withdrawAmount < 0) {
        message.error('提现金额不可小于零');
        isShow.value = false;
      } else {
        if (!formValue.value.withdrawMethod) {
          message.error('请选择提现方式在进行提现');
          isShow.value = false;
        } else {
          if (formValue.value.withdrawMethod == '1' && !formValue.value.cardHolder) {
            message.error('请输入持卡人');
            isShow.value = false;
          } else {
            formValue.value.txPassword = md5(formValue.value.txPassword)
            drawMoney(formValue.value).then((val) => {
              console.log(formValue.value);
              if (val.data.sysHead.retCd !== '000000') {
                message.error(val.data.sysHead.retInf);
                isShow.value = false;
              } else {
                message.success('提现成功');
                formValue.value.cardHolder = '';
                clear();
                disabled.value = false;
                isShow.value = false;
              }
            });
          }
        }
      }
    } else {
      message.error('提现失败');
      isShow.value = false;
    }
  });
};
</script>
<style lang="less">
.button {
  width: 20px;
  height: 20px;
  padding: 0 !important;
  margin-left: 8px;
  border-radius: 10px;
}
</style>